<?php

if ( 'on' == get_site_option( 'bpdev-widgets-status' ) )
	add_action( 'widgets_init', 'bpdev_widgets_members_wall_init' );
elseif ( !function_exists( 'bpdev_widgets_setup_globals' ) )
	add_action( 'widgets_init', 'bpdev_widgets_members_wall_init' );

function bpdev_widgets_members_wall_init() {

	global $bp;

	if ( !function_exists( 'register_sidebar_widget' ) )
		return;

	function bpdev_widgets_members_wall( $args ) {
		global $current_blog, $bp;
		
	extract($args);
		$options = get_blog_option( $current_blog->blog_id, 'bpdev_widgets_members_wall' );

		echo $before_widget;
		echo $before_title . 'Members Wall' . $after_title;

		$users = BP_Core_User::get_newest_users( $options['max_members'] );

		if ( $users['users'] ) :

			?>

			<div class="avatar-block">

			<?php

			foreach ( (array) $users['users'] as $user ) :

				?>

				<div class="item-avatar">
					<a href="<?php echo bp_core_get_userurl($user->user_id) ?>" title="<?php bp_fetch_user_fullname( $user->user_id, true ) ?>"><?php echo bp_core_get_avatar( $user->user_id, 1 ) ?></a>
				</div>

				<?php

			endforeach;

			?>

			</div>

			<?php 

			if ( function_exists('wp_nonce_field') )
				wp_nonce_field( 'bp_core_widget_members', '_wpnonce-members' );

			?>

			<input type="hidden" name="bpdev-widgets-members-wall-max-members" id="bpdev-widgets-members-wall-max-members" value="<?php echo $options['max_members'] ?>" />

		<?php else: ?>
			<div class="widget-error">
				<?php _e('There are no friends currently online.', 'buddypress') ?>
			</div>

		<?php endif; ?>

			<div class="clear"></div>

		<?php echo $after_widget; ?> 
		
	<?php
	}

	function bpdev_widgets_members_wall_control() {
		global $current_blog;
		
		$options = $newoptions = get_blog_option( $current_blog->blog_id, 'bpdev_widgets_members_wall' );

		if ( $_POST['bpdev-widgets-members-wall-submit'] ) {
			$newoptions['max_members'] = strip_tags( stripslashes( $_POST['bpdev-widgets-members-wall-max-members'] ) );
		}
		
		if ( $options != $newoptions ) {
			$options = $newoptions;
			update_blog_option( $current_blog->blog_id, 'bpdev_widgets_members_wall', $options );
		}
		
		$max_members = attribute_escape( $options['max_members'] );
	?>
			<p><label for="bpdev-widgets-members-wall-max-members"><?php _e('Maximum number of members to show:', 'buddypress'); ?><br /><input class="widefat" id="bpdev-widgets-members-wall-max-members" name="bpdev-widgets-members-wall-max-members" type="text" value="<?php echo $max_members; ?>" style="width: 30%" /></label></p>
			<input type="hidden" id="bpdev-widgets-members-wall-submit" name="bpdev-widgets-members-wall-submit" value="1" />
	<?php
	}

	register_sidebar_widget( 'BPDEV Members Wall', 'bpdev_widgets_members_wall' );
	register_widget_control( 'BPDEV Members Wall', 'bpdev_widgets_members_wall_control' );

}

?>